const namespace = 'GS.'

/**
 * cache.set('demo.abc', 1234);
 * cache.set('demo.test', 1234, 60); // 60秒后过期
 * cache.get('GS.demo.test')
 */
class cache {
  /**
   * @param key
   * @param value
   * @param expired 以秒为单位
   */
  set(key, value, expired) {

    if (!(expired === undefined)) {
      expired = expired * 1000 + (new Date()).getTime()
      value = { value, expired }
    }

    window.localStorage.setItem(namespace + key, JSON.stringify(value))
  }

  get(key) {
    const value = JSON.parse(window.localStorage.getItem(namespace + key))

    if (value && value.hasOwnProperty('expired')) {

      /** 如果没过期，则返回值 */
      if (value.expired >= (new Date()).getTime()) return value.value

      /** 已过期，清除值; 并返回 undefined */
      this.remove(key)
      return undefined
    }

    return value
  }

  keys() {
    return Object.keys(window.localStorage)
  }

  all() {
    const keys = Object.keys(window.localStorage)
    const rets = {}
    keys.forEach(key => (rets[key] = JSON.parse(window.localStorage[key])))
    return rets
  }

  remove(key) {
    window.localStorage.removeItem(namespace + key)
  }

  clear() {
    window.localStorage.clear()
  }
}

export default new cache()
